package com.makejl.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class SendMail {
	private static String server = "xxx";// smtp主机名。
	private static String from = "xxx@1.com";// 发送方邮件地址
	private static String pw = "123456";// 发送方邮件密码。

	private static String subject = "主题";

	private static String mailContent = "";// 邮件正文

	private static String mailContent1 = "<p>欢迎你注册。</p>";
	private static String mailContent2 = "<p>这是一封来自的注册确认信，请点击下面的链接地址，激活账号完成注册：</p>";
	private static String mailContent3 = "<p>(如果你无法点击此链接，请将上面的链接地址复制到你的浏览器地址栏中，打开页面即可)</p>";
	private static String mailContent4 = "<p>幽默365，美好每一天</p>";
	private static String mailContent5 = "<br/><p>(这是一封自动产生的email，请勿回复。)</p>";
	private static String mailContent6 = "<br/><p>服务信箱：<a href='mailto:admin@youmo365.com'>admin@youmo365.com</a></p>";
	private static String mailContent7 = "<p><a href='http://www.youmo365.com'>http://www.youmo365.com</a></p>";
	private static Logger Log = Logger.getLogger(SendMail.class);

	public synchronized void send(String to, String nickname, String url) {

		Properties props = new Properties();
		Session sendMailSession;
		// Store store;
		Transport transport;
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", server);
		props.put("mail.smtp.user", from);
		props.put("mail.smtp.password", pw);

		sendMailSession = Session.getInstance(props, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() // 邮件安全认证。
			{
				return new PasswordAuthentication(from, pw);
			}
		});

		Message newMessage = new MimeMessage(sendMailSession);
		try {
			try {
				newMessage.setFrom(new InternetAddress(from,"Youmo365"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				newMessage.setRecipient(Message.RecipientType.TO,
						new InternetAddress(to));
			newMessage.setSubject(subject);
			newMessage.setSentDate(new Date());
			mailContent += new Date().toLocaleString();
			newMessage.setText(mailContent);
			String content = "<p>" + nickname + "</p>" + mailContent1
					+ mailContent2;
			content += "<p><a href='" + url + "'>" + url + "</a></p>";
			content += mailContent3 + mailContent4 + mailContent5
					+ mailContent6+mailContent7;
			newMessage.setContent(content, "text/html;charset=GB2312");
			transport = sendMailSession.getTransport("smtp");

			Transport.send(newMessage);

		} catch (MessagingException ex) {
			Log.fatal("mail failed to:" + to);
		}
	}

}